﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using System.Xml;
using Coffee_Restaurant.DAL;
using Coffee_Restaurant.Database;
using Coffee_Restaurant.Forms.DinnerMenus;
using Coffee_Restaurant.UserControls;
using MetroFramework;
using MetroFramework.Controls;
using MetroFramework.Forms;

namespace Coffee_Restaurant
{
    public partial class Main : MetroForm
    {
        Loading loading;
        private int currentOrderIdSelect = 0;
        private int next = 99;
        public Main()
        {
            InitializeComponent();
        }

        //esc to exit
        protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
        {
            if (keyData == Keys.Escape)
            {
                this.Close();
                return true;
            }
            return base.ProcessCmdKey(ref msg, keyData);
        }

        private void Main_Load(object sender, EventArgs e)
        {
            this.WindowState = FormWindowState.Maximized;// show control box
            timerLoading.Start();
            loading = new Loading();
            loading.ShowDialog();
            //splitContainer2.Panel1Collapsed = true;// an table detail
            timerFadeTableDetail.Tick += timerTableDetailFadeOut_Tick;
            timerFadeTableDetail.Start();
            //load style default
            var style = AppSettingDa.GetValue("Style");
            if (style != null)
            {
                SetStyleColor(int.Parse(style));
            }
        }


        #region quan ly kho hang

        private int ItemCategoryId { get; set; }

        /// <summary>
        /// event select danh muc thi se load du lieu tuong ung
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void treeViewCategory_AfterSelect(object sender, TreeViewEventArgs e)
        {
            ItemCategoryId = Convert.ToInt32(itemManager1.treeViewItemCategory.Nodes[e.Node.Index].Name);
            itemManager1.IdCategory = ItemCategoryId;
            //load cac mat hang thuoc nhom danh muc theo ID
            if (ItemCategoryId == 0)
                LoadItems(null);
            else
                LoadItems(ItemCategoryId);

        }


        public void LoadCategoryItems()
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.sp_ItemCategories().ToList();
                var sumCount = db.sp_ItemCategories().Sum(x => x.CountItems);
                itemManager1.treeViewItemCategory.Nodes.Clear();
                itemManager1.treeViewItemCategory.Nodes.Add("0", "Tất cả (" + sumCount + ")");
                foreach (var itemc in model)
                {
                    itemManager1.treeViewItemCategory.Nodes.Add(itemc.ItemCategoriesId.ToString(), itemc.Name + " (" + itemc.CountItems + ")");
                }
            }
        }

        public void LoadItems(int? id)
        {
            using (var db = new DatabaseEntities())
            {
                //clear trc khi load
                itemManager1.dataGridViewItems.Rows.Clear();
                //mac dinh la load tat ca
                var model = db.Items.ToList();
                if (id != null)
                {
                    //neu truyen vao id thi load theo id
                    model = db.Items.Where(t => t.ItemCategoriesId == ItemCategoryId).ToList();
                }
                for (int i = 0; i < model.Count; i++)
                {
                    var item = model[i];
                    var row = new object[itemManager1.dataGridViewItems.ColumnCount];
                    row[0] = i + 1;
                    row[1] = item.ItemId;
                    row[2] = item.Name;
                    row[3] = item.Unit;
                    row[4] = item.Price;
                    row[5] = ItemCategoryDa.GetName(item.ItemCategoriesId);
                    row[6] = item.InWarehouse;
                    row[7] = item.Description;
                    itemManager1.dataGridViewItems.Rows.Insert(i, row);
                }
                itemManager1.dataGridViewItems.ClearSelection(); // disable auto selected row
            }
        }
        #endregion

        /// <summary>
        /// change themes color
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void metroLink1_Click(object sender, EventArgs e)
        {
            var m = new Random();
            next = m.Next(0, 13);
            SetStyleColor(next);

        }

        private void SetStyleColor(int number)
        {
            var style = (MetroColorStyle)number;

            //metroLink1.Style = style; //set cho metrolink
            this.Style = style; // set cho main
            metroStyleManager1.Style = style; //set cho toan ung dung
        }

        private void timerLoading_Tick(object sender, EventArgs e)
        {
            loading.metroProgressBar1.Value += 100;
            //neu 100% thi tat thong bao
            if (loading.metroProgressBar1.Value == 20)
            {
                loading.metroLabel1.Text = "Hoàn tất";
            }
            if (loading.metroProgressBar1.Value == 80)
            {
                loading.metroLabel1.Text = "Bắt đầu sử dụng";
            }
            if (loading.metroProgressBar1.Value >= 100)
            {
                //Application.DoEvents();
                listTable1.LoadDataArea();
                listTable1.AddFormTableDetails += AddFormTableDetails;
                timerLoading.Stop();
                loading.Close();
            }
        }

        public void AddFormTableDetails(object sender, ListTable.MyClass e)
        {
            tableDetails1.lblNumberTable.Text = "Bàn số " + e.text;

            splitContainer2.Panel1Collapsed = false; //show table detail
            if (splitContainer2.SplitterDistance == 0)
            {
                timerFadeTableDetail.Tick += timerTableDetailFadeIn_Tick;
                timerFadeTableDetail.Start();
            }

            //remove event exist
            tableDetails1.metroButton1.Click -= MetroButton1OnClick;
            //readd event
            tableDetails1.metroButton1.Click += MetroButton1OnClick;

            //button goi mon
            //remove event exist
            tableDetails1.metroButton2.Click -= MetroButton2OnClick;
            //readd event
            tableDetails1.metroButton2.Click += MetroButton2OnClick;

            //remove event exist
            tableDetails1.metroButton3.Click -= metroButton3_Click;
            //readd event
            tableDetails1.metroButton3.Click += metroButton3_Click;
        }

        private void MetroButton2OnClick(object sender, EventArgs eventArgs)
        {
            var button = sender as MetroButton;
            if (button != null && button.Text.Contains("Gọi món"))
            {
                tableDetails1.metroButton2.Text = "<<";
                var menuToSell = new MenuToSell { Dock = DockStyle.Left };
                //kiem tra xem co control nay chua. chua co thi add vao
                if (!splitContainer2.Panel2.Controls.ContainsKey("MenuToSell"))
                    splitContainer2.Panel2.Controls.Add(menuToSell);
            }
            else
            {
                tableDetails1.metroButton2.Text = "Gọi món";
                splitContainer2.Panel2.Controls.RemoveByKey("MenuToSell");
            }

        }

        private void MetroButton1OnClick(object sender, EventArgs eventArgs)
        {
            try
            {
                var btn = sender as MetroButton;
                if (btn != null)
                {
                    switch (btn.Tag.ToString())
                    {
                        case "huyban":
                            btn.Tag = "moban";
                            btn.Text = "Mở bàn";
                            backgroundWorkerHuyBan.RunWorkerAsync();
                            break;
                        case "moban":
                            btn.Tag = "huyban";
                            btn.Text = "Hủy Bàn";
                            //backgroundWorkerDatBan.RunWorkerAsync();
                            if (currentOrderIdSelect > 0)
                            {
                                Moban();
                            }
                            else
                            {
                                currentOrderIdSelect = DatBan();
                                Moban();
                            }
                            break;
                    }
                }
            }
            catch (Exception)
            {
                DialogResult = MetroMessageBox.Show(this, "Đây là thông báo lỗi vui lòng chọn `Abort (Hủy)`, `Retry (Thử lại)` hoặc `Ignore (Bỏ qua)`", "Có lỗi xảy ra", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);

            }
        }

        void metroButton3_Click(object sender, EventArgs e)
        {
            try
            {
                var btn = sender as MetroButton;
                if (btn != null)
                {
                    switch (btn.Tag.ToString())
                    {
                        case "huydat":
                            btn.Tag = "datban";
                            btn.Text = "Đặt bàn";
                            backgroundWorkerHuyBan.RunWorkerAsync();
                            break;
                        case "datban":
                            btn.Tag = "huydat";
                            btn.Text = "Hủy đặt";
                            backgroundWorkerDatBan.RunWorkerAsync();
                            break;
                    }
                }
            }
            catch (Exception)
            {
                DialogResult = MetroMessageBox.Show(this, "Đây là thông báo lỗi vui lòng chọn `Abort (Hủy)`, `Retry (Thử lại)` hoặc `Ignore (Bỏ qua)`", "Có lỗi xảy ra", MessageBoxButtons.AbortRetryIgnore, MessageBoxIcon.Error);

            }
        }

        public int Moban()
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.Orders.FirstOrDefault(x => x.OrderId == currentOrderIdSelect);
                if (model != null)
                {
                    model.BeginTime = DateTime.Now;
                    model.Status = "Chưa gọi món";
                    SetData(model);
                    SetButtonSauKhiMoBan();
                    return db.SaveChanges();
                }
                return 0;
            }
        }

        public int DatBan()
        {
            using (var db = new DatabaseEntities())
            {
                var guid = Guid.NewGuid().ToString();
                var order = new Order
                {
                    Status = "Bàn đã đặt trước",
                    TypeCustomer = "Khách thường",
                    Requester = "Admin",
                    TotalMoney = 0,
                    SubMoney = 0,
                    TaxVat = 0,
                    GuiId = guid

                };
                db.Orders.Add(order);
                if (db.SaveChanges() > 0)
                {
                    //dat ban thanh cong tra ve Id
                    var model = db.Orders.FirstOrDefault(x => x.GuiId == guid);
                    if (model != null)
                    {
                        SetData(model);
                        return model.OrderId;
                    }
                }
                return 0;
            }
        }
        #region set button sau khi mo ban thanh cong
        public void SetButtonSauKhiMoBan()
        {
            //set button
            tableDetails1.metroButton3.Text = "Chuyển";
            tableDetails1.metroButton3.Click -= metroButton3_Click; //xoa event cu
            tableDetails1.metroButton3.Click -= Chuyen_Click; //xoa event cu
            tableDetails1.metroButton3.Click += Chuyen_Click;

            tableDetails1.metroButton4.Text = "Nhập";
            tableDetails1.metroButton4.Click -= Nhap_Click; //xoa event cu
            tableDetails1.metroButton4.Click += Nhap_Click;

            tableDetails1.metroButton5.Text = "Tách";
            tableDetails1.metroButton5.Click -= Tach_Click; //xoa event cu
            tableDetails1.metroButton5.Click += Tach_Click;

            tableDetails1.metroButton6.Text = "Ghép";
            tableDetails1.metroButton6.Click -= Ghep_Click; //xoa event cu
            tableDetails1.metroButton6.Click += Ghep_Click;
        }


        private void Chuyen_Click(object sender, EventArgs e)
        {
        }
        private void Nhap_Click(object sender, EventArgs e)
        {
        }
        private void Tach_Click(object sender, EventArgs e)
        {
        }
        private void Ghep_Click(object sender, EventArgs e)
        {
        }

        #endregion

        #region set button sau khi huy ban
        public void SetButtonSauKhiHuyBan()
        {
            //set button
            tableDetails1.metroButton3.Text = "Đặt bàn";
            tableDetails1.metroButton3.Tag = "datban";
            tableDetails1.metroButton3.Click -= metroButton3_Click;
            tableDetails1.metroButton3.Click += metroButton3_Click;

            tableDetails1.metroButton4.Text = "";
            tableDetails1.metroButton4.Click -= Nhap_Click;

            tableDetails1.metroButton5.Text = "";
            tableDetails1.metroButton5.Click -= Tach_Click;

            tableDetails1.metroButton6.Text = "";
            tableDetails1.metroButton6.Click -= Ghep_Click;
        }

        #endregion


        public void SetData(Order model)
        {
            tableDetails1.lblTimeIn.Text = model.BeginTime.ToString();
            tableDetails1.lblStatus.Text = model.Status;
            tableDetails1.lblCustomerType.Text = model.TypeCustomer;
            tableDetails1.lblRequester.Text = model.Requester;
            tableDetails1.metroLabel6.Text = String.Format("Tổng tiền: {0:0}đ    Phụ phí: {1}", model.TotalMoney, model.SubMoney);
            tableDetails1.metroLabel7.Text = String.Format("Giảm giá: {0}    VAT: {1}%", 0, model.TaxVat);
            tableDetails1.metroLabel8.Text = String.Format("Thành tiền: {0:0}đ", (model.TotalMoney + model.SubMoney));
        }

        public void SetDataEmpty()
        {
            tableDetails1.lblTimeIn.Text = "";
            tableDetails1.lblStatus.Text = "";
            tableDetails1.lblCustomerType.Text = "";
            tableDetails1.lblRequester.Text = "";
            tableDetails1.metroLabel6.Text = "";
            tableDetails1.metroLabel7.Text = "Thời điểm phục vụ gần đây nhất";
            tableDetails1.metroLabel8.Text = "1:00 PM 20/11/2014";
            currentOrderIdSelect = 0; //reset ve 0
        }

        /// <summary>
        /// huy dat ban
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public int HuyDat(int id)
        {
            using (var db = new DatabaseEntities())
            {
                var model = db.Orders.FirstOrDefault(x => x.OrderId == id);
                if (model != null)
                {
                    db.Orders.Remove(model);
                    if (db.SaveChanges() > 0)
                    {
                        SetDataEmpty();
                        SetButtonSauKhiHuyBan();
                        return 1;
                    }
                }
                return 0;
            }
        }

        private void Main_FormClosing(object sender, FormClosingEventArgs e)
        {
            //save to db appsetting
            if (next.ToString() != "99")
            {
                AppSettingDa.Update("Style", next.ToString());
            }
        }

        #region fadetabledetail
        private bool flagfade = false;
        private void timerTableDetailFadeIn_Tick(object sender, EventArgs e)
        {
            if (flagfade)
            {
                if (splitContainer2.SplitterDistance >= 300)
                {
                    timerFadeTableDetail.Stop();
                    flagfade = false; //cho phep fadeout
                }
                else
                {
                    splitContainer2.SplitterDistance += 30;
                }
            }
        }
        private void timerTableDetailFadeOut_Tick(object sender, EventArgs e)
        {
            if (!flagfade)
            {
                if (splitContainer2.SplitterDistance == 0)
                {
                    timerFadeTableDetail.Stop();
                    flagfade = true; //cho phep fadeint
                    tableDetails1.Enabled = true;
                }
                else
                {
                    splitContainer2.SplitterDistance -= 60;
                }
            }

        }
        #endregion

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            if (currentOrderIdSelect > 0)
            {
                HuyDat(currentOrderIdSelect);
            }
        }

        private void backgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            currentOrderIdSelect = DatBan();
        }

        //select tab
        private void metroTabControl1_Selecting(object sender, TabControlCancelEventArgs e)
        {
            //load data tab quan ly kho hang
            if (e.TabPage.Name == "tabKhohang")
            {
                if (itemManager1.treeViewItemCategory.Nodes.Count <= 0)
                {
                    LoadCategoryItems();
                    //add event
                    itemManager1.treeViewItemCategory.AfterSelect -= treeViewCategory_AfterSelect;
                    itemManager1.treeViewItemCategory.AfterSelect += treeViewCategory_AfterSelect;
                    txtKeyword.TextChanged += itemManager1.txtKeyword_TextChanged;
                }
                if (itemManager1.dataGridViewItems.Rows.Count <= 1)
                {
                    LoadItems(null);
                }
            }
            //tab thuc don
            if (e.TabPage.Name == "tabThucdon")
            {
                if (dinnerMenuManager1.treeViewItemCategory.Nodes.Count <= 0)
                {
                    dinnerMenuManager1.LoadCategoryItems();
                    //dinnerMenuManager1.LoadDinnerMenu(null);
                    //LoadCategoryItems();
                    //add event
                    dinnerMenuManager1.treeViewItemCategory.AfterSelect -= dinnerMenuManager1.treeViewCategory_AfterSelect;
                    dinnerMenuManager1.treeViewItemCategory.AfterSelect += dinnerMenuManager1.treeViewCategory_AfterSelect;
                }
                //if (itemManager1.dataGridViewItems.Rows.Count <= 1)
                //{
                //    LoadItems(null);
                //}
            }
        }


    }
}
